package com.langxin.erp.core.exception;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Properties;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.SimpleMappingExceptionResolver;

public class RestExceptionResolver extends SimpleMappingExceptionResolver {

	private final static Logger log = LoggerFactory.getLogger(RestExceptionResolver.class);
	/** The default name of the exception attribute: "exception". */
	public static final String DEFAULT_EXCEPTION_ATTRIBUTE = "exception";

	private Properties exceptionMappings;

	@Override
	protected ModelAndView doResolveException(HttpServletRequest request, HttpServletResponse response, Object handler,
			Exception ex) {

		// Expose ModelAndView for chosen error view.
		String viewName = "error/500.jsp";
		log.error(ex.getMessage());
		{// JSP格式返回
			if (!(request.getHeader("accept").indexOf("application/json") > -1
					|| (request.getHeader("X-Requested-With") != null && request.getHeader("X-Requested-With").indexOf(
							"XMLHttpRequest") > -1) || (request.getHeader("Content-Type") != null && request.getHeader(
					"Content-Type").indexOf("multipart/form-data") > -1))) {
				// 如果不是异步请求
				// Apply HTTP status code for error views, if specified.
				// Only apply it if we're processing a top-level request.
				Integer statusCode = determineStatusCode(request, viewName);
				if (statusCode != null) {
					applyStatusCodeIfPossible(request, response, statusCode);
				}
                ModelAndView mav = getModelAndView(viewName, ex, request);
				mav.addObject("ex", StringUtils.isEmpty(ex.getMessage()) ? "系统未知错误" : ex.getMessage());
				return mav;
			} else {// JSON格式返回
				try {
					response.setContentType("text/plain; charset=UTF-8");
					PrintWriter writer = response.getWriter();
					writer.write(ex.getMessage());
					writer.flush();
					writer.close();
				} catch (IOException e) {
					log.error(e.getMessage());
				}
				return null;
			}
		}
	}

	public Properties getExceptionMappings() {
		return exceptionMappings;
	}

	public void setExceptionMappings(Properties exceptionMappings) {
		this.exceptionMappings = exceptionMappings;
		super.setExceptionMappings(exceptionMappings);
	}

}
